package cn.kailangtu.myapplication;

import static android.view.View.VISIBLE;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.BinderThread;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.fragment.NavHostFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import cn.kailangtu.myapplication.consts.YuyinType;
import cn.kailangtu.myapplication.data.Address;
import cn.kailangtu.myapplication.data.Tool;
import cn.kailangtu.myapplication.data.yemian;
import cn.kailangtu.myapplication.databinding.FragmentFirstBinding;
import cn.kailangtu.myapplication.events.CloseKeyboardEvent;
import cn.kailangtu.myapplication.events.OpenKeyboardEvent;
import cn.kailangtu.myapplication.events.PlayYuyin;
import cn.kailangtu.myapplication.events.SerialData;
import cn.kailangtu.myapplication.events.SerialDataRS481;
import cn.kailangtu.myapplication.events.SerialPortCmd;
import cn.kailangtu.myapplication.events.Shuaxing灯Event;
import cn.kailangtu.myapplication.events.eventData.KeyboardInputType;
import cn.kailangtu.myapplication.events.刷新页面事件;
import cn.kailangtu.myapplication.events.灯刷新;
import cn.kailangtu.myapplication.fragment.BaseFragment;
import cn.kailangtu.myapplication.specialview.ElectricView;
import cn.kailangtu.myapplication.tools.FomaterUtils;
import cn.kailangtu.myapplication.tools.MediaPlayerUtils;
import cn.kailangtu.myapplication.view.VirtualKeyboardFragment;
import cn.kailangtu.serialport.ModbusError;
import cn.kailangtu.serialport.ModbusSlave;

public class FirstFragment extends BaseFragment {

    private FragmentFirstBinding binding;




    boolean isInit = false;

    long lastPlayLow = System.currentTimeMillis();

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

       ElectricView.getInstance().init(binding.ivElectricTop1,binding.ivElectricTop2,binding.ivElectricTop3,binding.ivElectricTop4,binding.ivElectricTop5,binding.ivElectricTop6,binding.ivElectricTop7,binding.ivElectricTop8,binding.ivElectricTop9,binding.ivElectricTop10,binding.ivElectricTop11,binding.ivElectricTop12);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        String t=format.format(new Date())+" "+FomaterUtils.get星期();
        binding.TextViewTime.setText(t);
        EventBus.getDefault().post(new 刷新页面事件());

        binding.buttonShexiangtou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });

        binding.buttonSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment2);
            }
        });
        binding.guzhangcaidan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment1);

                 */

                OpenKeyboardEvent event = new OpenKeyboardEvent(KeyboardInputType.PASSWORD, 1);
                event.setMaxValue(12);
                event.setMinValue(0);
                event.setInitialValue("");
                EventBus.getDefault().post(event);
            }
        });

        isInit = true;
    }
    int clickCount = 0;

    boolean isLogCmd= false;



    static float  currIndec =0;
    static long lastTime=0;
    public void testSpeed()
    {
        SystemClock.sleep(1000);
        final byte[] a1 = {0};
        new Thread(new Runnable() {
            @Override
            public void run() {
                Random r = new Random();
                while(true) {
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            currIndec=currIndec+1f;
                            currIndec = r.nextInt(50);
                            if(currIndec >180)
                            {
                                currIndec = 0;
                                // DashboardView.durationValue = 300;
                                //binding.dashView.udDataSpeed(currIndec);

                            }
                           // ModbusRtuMaster modbusRtuMaster=new ModbusRtuMaster();
                            ModbusSlave modbusSlave=new ModbusSlave();
                            a1[0] = (byte) (a1[0] +1);
                            try {
                                modbusSlave.readCoils(1,0, 3);
                            } catch (ModbusError e) {
                                throw new RuntimeException(e);
                            }
                         //   Log.e("wwwwww", modbusSlave.toString());
                            /********///这个老版本还在
                            //binding.dashView.setDegreeOffset(currIndec);
                            /**************/
                            Log.d("SHOOTLEE_OFFSET","设置新值:开始"+currIndec * 2);
                            binding.dashView2.setDegreeOffset(currIndec*2);
                            Log.d("SHOOTLEE_OFFSET","设置新值:结束");
                          //  binding.buttonFirst2.setText(""+ currIndec);
                       //     binding.buttonSudu.setText(""+ currIndec);
                            binding.dianchidianliang.setText(""+  currIndec*2+"%");
                            long curr = System.currentTimeMillis() -lastTime;
                            Log.i("TAGTAGTAGTAG", "startAnimation: running:" +curr+  "--started--"+currIndec  );
                            lastTime = System.currentTimeMillis();
                        }
                    });

                    SystemClock.sleep(1000);
                    //  binding.dashView.closeAnimation();
                }
            }
        }).start();


    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(SerialPortCmd event) {
//        if(isLogCmd) {
//            if(binding.tvSerialPort.getLineCount()> 800)
//            {
//                binding.tvSerialPort.setText("");
//            }
//            String cmd = event.toString().toUpperCase();
//            if(cmd.indexOf("2F4")> -1) {
//                binding.tvSerialPort.append(event.toString() + "\r\n");
//            }
//        }
//    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SerialData event){

        //时间
        if(event.getAtime()!=null && isInit) {
            binding.TextViewTime.setText(event.getAtime()+" "+FomaterUtils.get星期());
            yemian.getInstance().页面1(1,this.getActivity());
        }

    }

    long lastPlayPowerTime = 0;
    int lastPowerType = -1;
    private boolean canPlayPower(int powerType)
    {
        if(System.currentTimeMillis() - lastPlayPowerTime > 30000 || (lastPowerType != powerType))
        {
            lastPlayPowerTime = System.currentTimeMillis();
            lastPowerType = powerType;
            return true;
        }
        return false;
    }



    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent(PlayYuyin playYuyin) {
        if(isInit) {
            switch (playYuyin.getIndex()) {
                case YuyinType.POWER_10:

                    if (System.currentTimeMillis() - lastPlayLow > 3000) {
                        MediaPlayerUtils.getInstance().playPowerLow();
                    }
                    break;
                case YuyinType.POWER_20:
                    MediaPlayerUtils.getInstance().playPower20();
                    break;
                case YuyinType.POWER_30:
                    MediaPlayerUtils.getInstance().playPower30();
                    break;
//            case YuyinType.TURN_START:
//                MediaPlayerUtils.getInstance().playZhuanxiangStart();
//                break;
//            case YuyinType.TURN_END:
//                MediaPlayerUtils.getInstance().playZhuanxiangEnd();
//                break;
//            case YuyinType.TURN_PLAY:
//                MediaPlayerUtils.getInstance().playZhuanxiang();
//                break;
                case YuyinType.TURN_kai:
                    MediaPlayerUtils.getInstance().playZhuanxiang1();
                    break;
                case YuyinType.TURN_guan:
                    MediaPlayerUtils.getInstance().playZhuanxiang2();
                    break;
            }
        }

        // if(playYuyin.getIndex()== YuyinType.TURN_END){}

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SerialDataRS481 event){




    }
    //BYTE转成二进制字符串
        public  String byteToBinaryString(byte b) {
            StringBuilder binaryString = new StringBuilder(8);
            for (int i = 0; i < 8; i++) {
                // 通过位运算获取当前位的值（0或1）
                int bit = (b >> i) & 1;
                // 将当前位的值追加到StringBuilder中
                binaryString.append(bit);
            }
            // 返回构建好的二进制字符串
            return binaryString.toString();
        }
        //BYTE转成bool
        public  boolean[] byteToBooleanArray(byte b) {
            boolean[] boolArray = new boolean[8];
            for (int i = 0; i < 8; i++) {
                // 通过位运算检查当前位是否为1
                boolArray[i] = ((b >> i) & 1) == 1;
            }
            return boolArray;
        }

        //合并成int
        public static int combineBytesToInt(byte byte1, byte byte2) {
            // 将byte1左移8位，空出的低位由byte2填充
            return (byte1 << 8) | (byte2 & 0xFF);
        }
    //合并成int32
        public static int combineBytesToInt32(byte byte0, byte byte1, byte byte2, byte byte3) {
            return ((byte0 << 24) & 0xFF000000) |
                    ((byte1 << 16) & 0x00FF0000) |
                    ((byte2 << 8)  & 0x0000FF00) |
                    ((byte3)       & 0x000000FF);
        }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void yemian(){
        yemian.getInstance().页面1(1,this.getActivity());
    }
    public void onMessageEvent(刷新页面事件 event){
        if(isInit) {
            yemian.getInstance().页面1(1, this.getActivity());
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(OpenKeyboardEvent event) {
//        VirtualKeyboardFragment virtualKeyboardFragment = VirtualKeyboardFragment.newInstance(event.getInputType(), event.getRequestCode());
//        virtualKeyboardFragment.setInitialValue("");
//        virtualKeyboardFragment.setInputRules(event.getMinLength(),event.getMaxLength(),event.getMinValue(),event.getMaxValue());

        binding.rlKeyboardContainer.setVisibility(View.VISIBLE);
        binding.rlKeyboardContainer.setClickable(true);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CloseKeyboardEvent event) {
        if (event.isConfirmed()) {
            if(event.getResult().equals("250828"))
            {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment1);
            }
        }
        binding.rlKeyboardContainer.setVisibility(View.GONE);
        binding.rlKeyboardContainer.setClickable(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(灯刷新 event)
    {
        if(isInit) {
            if (event.get左转灯() != 0) {
                binding.zuozhuanxiangdeng.setVisibility(event.get左转灯() == 1 ? VISIBLE : View.INVISIBLE);
                if(Address.getInstance().双闪灯)
                {
                    binding.shuangshan.setVisibility(event.get左转灯() == 1 ? VISIBLE : View.INVISIBLE);
                }
            }
            if (event.get右转灯() != 0) {
                binding.youzhuanxiangdeng.setVisibility(event.get右转灯() == 1 ? VISIBLE : View.INVISIBLE);
            }
            if (event.get双闪灯() != 0) {
                int view = event.get双闪灯() == 1 ? VISIBLE : View.INVISIBLE;
                binding.shuangshan.setVisibility(view);
                binding.zuozhuanxiangdeng.setVisibility(view);
                binding.youzhuanxiangdeng.setVisibility(view);
            }

        }
    }


    //EventBus  推出
    @Override
    public void onStop(){
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}